'use strict';

app.controller('demandCtrl', ['$scope', '$http', '$stateParams', '$rootScope', '$filter', '$location', '$timeout','lodash', function ($scope, $http, $stateParams, $rootScope, $filter, $location, $timeout,lodash) {
    $scope.urlKeyword="";
    $rootScope.initBreadcrumb($scope.breadcrumb);
    //页面加载时，给headerElement设置元素
    $rootScope.initHeaderElements($scope.settings);
    // $scope.settings.searchEle = {
    //     show: true,                   //显示查询框
    //     func: function(keyword) {     //点击查询框调用的方法
    //         $scope.urlKeyword = keyword ? keyword : "";
    //         getReqList();
    //     },
    //     blurFunc: function(keyword) {
    //         $scope.urlKeyword = keyword ? keyword : "";
    //     }
    // };
    var backUrl = {
        show: true,
        label: "返回",
        func: function () {
            $rootScope.backHistory();
        }
    }
    $scope.settings.btnEle.push(backUrl);
    //结束headerElement设置
    setStorage('brdBackUrl', $location.url())

    $scope.info = {
        selectType      : "list",  //list, file, flow, feature
        currentType     : "",
        daterminedV     : "",      //定版数据
        reqDetails      : [],      //文档详情数据
        reqSearch       : [],
        projectPlanInfo : {},
        reqRelateFlows  : [],
        relateFeatures  : [],
        flowDetails     : "",
        featureDetails  : "",
        jumpToFeature   : "",
        reqThdata : [          //req列表头属性【编号，产品设计，创建日期，立项，PDM负责人，项目，计划上线日，操作】
            {"thName": "产品设计标题",width:500},
            {"thName": "创建日期"},
            {"thName": "PDM负责人"},
            {"thName": "计划上线日"}
        ],
        reqPage  : {"isTrue": false},
        reqList  : {
            "trIsClick": false,
            "isOperation": {
                "Delete": {"isTrue": true, "msg": "移除"}
            },
            "tdName": [
                {"name": "reqName"},
                {"name": "reqCreateTime"},
                {"name": "reqChargerRealname"},
                {"name": "reqUseTime"}
            ]
        },
        projectPlanId : $stateParams.id ? $stateParams.id : null,
        reqListByPid   : [],   //根据项目计划查询出来的req列表数据
        sltReqItem     : "",   //默认选择的req数据
    };
    $scope.info.model = new go.GraphLinksModel([], []);
    $scope.info.mDiagram = null;
    $scope.info.paModel = new go.GraphLinksModel([]);

    $scope.props = {
        reqId : "",
    };

    getProjectPlanDetails();
    getProjectPlanList();


    //切换视图模式
    $scope.selectRadio = function(type) {
        $scope.info.currentType = type;
        $scope.info.daterminedV = "";
        if(type != "list") {
            getReqListByPid();
        }
    };

    //*****列表视图******/

    //获取项目计划详情（仅使用projectPlanName字段）
    function getProjectPlanDetails() {
        var url = matrix_product_url +"/projectPlan/getProjectPlans?containFinished=Y&projectPlanId="+ $scope.info.projectPlanId;
        $http.get(url).success(function(result) {
            if(result.code == "0") {
                $scope.info.projectPlanInfo = result.data[0];
                $scope.breadcrumb.push('项目计划',$scope.info.projectPlanInfo.projectPlanName);
                getProjectPlanStatus();
            } else {
                $rootScope.toasterErrorInfo(result.msg);
            }
        });
    };

    //获取项目计划状态
    function getProjectPlanStatus() {
        var url = sys_config_url +"/select/get?type=BRD_STATUS";
        $http.get(url).success(function(result) {
            if(result.code == "0") {
                $scope.info.status=result.data.BRD_STATUS;
                getReqList(result.data.BRD_STATUS);
            } else {
                $rootScope.toasterErrorInfo(result.desc);
            }
        });
    };

    //获取req列表
    function getReqList(projectPlanStatus) {
        var url = matrix_product_url +"/brdRequirement/getBrdRequirements?withFeatureDesc=0&projectPlanId="+ $scope.info.projectPlanId +"&keyword="+ $scope.urlKeyword;
        $http.get(url).success(function (data) {
            if (data.code == "0") {
                angular.forEach(data.data, function(d) {
                    d.crtname=d.reqName;
                    var item = lodash.findWhere(projectPlanStatus, {key: d.reqStatus});
                    d.statusName = item.value;
                    d.reqCreateTime = timestampToTime(d.reqCreateTime);
                    d.reqUseTime = timestampToTime(d.reqUseTime);
                });
                $scope.info.reqList.datas = data.data;
            } else {
                $rootScope.toasterErrorInfo(data.msg);
            }
        })
    };

    //获取产品设计列表
    function getProjectPlanList() {
        var url = matrix_product_url+"/brdRequirement/getBrdRequirements?withFeatureDesc=0";
        $http.get(url).success(function(result) {
            if(result.code == "0") {
                angular.forEach(result.data, function(plan) {
                    if(plan.reqStatus == "NEW" || plan.reqStatus == "DISSOCIATION") {
                        plan.crtname    = plan.reqName;
                        plan.selectTrue = false;
                        $scope.info.reqSearch.push(plan);
                    }
                });
            } else {
                $rootScope.toasterErrorInfo(data.msg);
            }
        });
    };

    //选择产品设计添加到需求列表
    $scope.addToReqList = function () {
        if(!$scope.info.selectReq) {
            $rootScope.toasterWarningInfo("请先选择产品设计");
            return false;
        }
        setStorage("join_projectPlan_id", $scope.info.projectPlanId);

        $scope.info.selectReq.reqCreateTime = timestampToTime($scope.info.selectReq.reqCreateTime);
        $scope.info.selectReq.reqUseTime = timestampToTime($scope.info.selectReq.reqUseTime);
        $scope.info.reqList.datas.push($scope.info.selectReq);
        var postParams = {
            projectPlanId : $scope.info.projectPlanId,
            reqIds        : lodash.pluck($scope.info.reqList.datas, "reqId"),
            tokenId       : getTokenId()
        };
        var url = matrix_product_url +"/projectPlan/saveProjectPlan";
        $http({
            method   : "post",
            url      : url,
            data     : JSON.stringify(postParams),
            headers : {"Content-Type": "application/json"}
        }).success(function(result) {
            if(result.code == "0") {
                lodash.remove($scope.info.reqSearch, {"reqId": $scope.info.selectReq.reqId});
                $scope.info.selectReq = "";
                getReqList($scope.info.status);
                $rootScope.toasterSuccessInfo("保存成功！");
            } else {
                lodash.remove($scope.info.reqList.datas, {"reqId": $scope.info.selectReq.reqId});
                $scope.info.selectReq = "";
                $rootScope.toasterErrorInfo(result.desc);
            }
        });
    }

    //删除选中的req
    $scope.deleteReq = function(req) {
        var confirmPrompt = {
            titleData: "提示",
            bodyData : "是否删除选中需求？"
        };
        $rootScope.confirmWindow(confirmPrompt, function (confirm) {
            if(confirm) {
                var url = matrix_product_url +"/projectPlan/updateProjectPlanReq?optMode=-1&projectPlanId="+ $scope.info.projectPlanId +"&reqIds="+ req.reqId;
                $http.get(url).success(function(result) {
                    if(result.code == "0") {
                        lodash.remove($scope.info.reqList.datas, {"reqId": req.reqId});
                        $scope.info.reqSearch.push(req)
                        $rootScope.toasterSuccessInfo("删除成功！");
                    } else {
                        $rootScope.toasterErrorInfo(result.desc);
                    }
                    if($scope.info.reqList.datas.length==0){
                        $scope.info.sltReqItem="";
                    }
                });
            }
        });
    };

    //更新需求
    $scope.reqUpdate = function (info) {
        window.location.href = "#/app/req/summary/" + info.reqId;
    }

    //*****文档视图******/

    //根据项目计划id查询req列表数据
    function getReqListByPid() {
        if(!$scope.info.projectPlanId) {
            $rootScope.toasterWarningInfo("项目计划id不能为空！");
            return false;
        }
        var url = matrix_product_url +"/brdRequirement/getBrdRequirements?projectPlanId="+ $scope.info.projectPlanId;
        $http.get(url).success(function(result) {
            if(result.code == "0") {
                if(!result.data) {
                    $rootScope.toasterWarningInfo("获取产品计划数据错误！");
                    return false;
                }
                angular.forEach(result.data, function(req) {
                    req.crtname = req.reqName;
                });
                $scope.info.reqListByPid = result.data;
                if(result.data.length > 0) {
                    $scope.info.sltReqItem = lodash.first(result.data);
                    validateReq($scope.info.sltReqItem);
                }
            } else {
                $rootScope.toasterErrorInfo(result.desc);
            }
        });
    };

    //校验当前产品设计是否已经定板
    function validateReq(sltItem) {
        var url = matrix_product_url +"/brdRequirement/getReqSubmitHistory?reqId="+ sltItem.reqId;
        $http.get(url).success(function(result) {
            if(result.code == "0") {
                if(result.data.length > 0) {
                    $scope.info.daterminedV = lodash.last(result.data);
                    $scope.props.reqId = $scope.info.sltReqItem.reqId;
                    if($scope.info.currentType == "flow") {
                        getReqRelateFlows($scope.info.sltReqItem.reqId);
                    }
                    if($scope.info.currentType == "feature") {
                        getReqRelateFeature($scope.info.sltReqItem.reqId);
                    }
                } else {
                    $scope.info.daterminedV = "";
                }
            } else {
                $rootScope.toasterErrorInfo(result.desc);
            }
        });
    };

    //切换产品设计列表方法
    $scope.selectReqItem = function(item) {
        validateReq(item);
        $scope.info.jumpToFeature = "";
        if($scope.info.currentType == "flow") {
            $scope.info.model = new go.GraphLinksModel([], []);
        }
        if($scope.info.currentType == "feature") {
            $scope.info.featureDetails = "";
        }
    };

    //*****流程视图******/

    //获取req关联的流程列表
    function getReqRelateFlows(reqId) {
        var url = matrix_product_url +"/flow/getReqFlows?reqId="+ reqId;
        $http.get(url).success(function(result) {
            if(result.code == "0") {
                $scope.info.reqRelateFlows = result.data;
            } else {
                $rootScope.toasterErrorInfo(result.desc);
            }
        });
    }

    //点击切换flow
    $scope.goTo = function(relate) {
        if(relate) {
            $scope.info.jumpToFeature = relate.id;
            getFlowDetails($scope.props.reqId, relate.id);
        }
    };

    //获取flow详情
    function getFlowDetails(reqId, flowId) {
        var url = matrix_product_url +"/flow/getFlowDetail?flowId="+ flowId +"&reqId="+ reqId;
        $http.get(url).success(function(result) {
            if(result.code == "0") {
                $scope.info.flowDetails = result.data;
                $scope.info.model = new go.GraphLinksModel(result.data.attrs.nodeDataArray, result.data.attrs.linkDataArray);
            } else {
                $rootScope.toasterErrorInfo(result.desc);
            }
        });
    };

    //*****功能点视图******/

    //获取req关联的功能点
    function getReqRelateFeature(reqId) {
        var url = matrix_product_url +"/feature/getAllFeatureForReq?reqId="+ reqId;
        $http.get(url).success(function(result) {
            if(result.code == "0") {
                $scope.info.relateFeatures = result.data;
            } else {
                $rootScope.toasterErrorInfo(result.desc);
            }
        });
    };
}]);